"""
订单API
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from decimal import Decimal
import uuid

from database import get_db
from database.base import Base, engine
from models.models import User
from models.order_models import Order, OrderItem
from schemas.order import CreateOrderRequest, OrderResponse, OrderItemResponse
from routers.dependencies import get_current_user
from tasks.orders import delete_unpaid_order

router = APIRouter(prefix="/api/orders", tags=["订单"])

# 确保表存在（仅第一次会创建）
try:
    Base.metadata.create_all(bind=engine)
except Exception:
    pass


@router.post("/", response_model=OrderResponse)
async def create_order(
    req: CreateOrderRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    创建订单：从购物车传入的 items 生成订单与订单项，返回唯一订单号
    """
    if not req.items:
        raise HTTPException(status_code=400, detail="订单项不能为空")

    order_no = uuid.uuid4().hex  # 全局唯一订单号
    total = Decimal("0.00")
    for it in req.items:
        total += Decimal(str(it.price)) * int(it.qty)

    order = Order(
        order_no=order_no,
        user_id=current_user.id,
        total_amount=total,
        status=0
    )
    db.add(order)
    db.flush()  # 获取order.id

    for it in req.items:
        db.add(OrderItem(
            order_id=order.id,
            goods_id=it.goods_id,
            name=it.name,
            price=Decimal(str(it.price)),
            qty=int(it.qty),
            image_url=it.image_url
        ))

    db.commit()
    db.refresh(order)

    # 调度“10分钟后检查并删除未支付订单”的任务（精确到单个订单）
    try:
        delete_unpaid_order.apply_async(args=[order.order_no], countdown=600)
    except Exception:
        # 如果 Celery 未启动，不影响主流程
        pass

    return OrderResponse(
        order_no=order.order_no,
        total_amount=order.total_amount,
        status=order.status,
        created_at=order.created_at,
        items=[OrderItemResponse(
            goods_id=i.goods_id, name=i.name, price=i.price, qty=i.qty, image_url=i.image_url
        ) for i in order.items]
    )


@router.get("/", response_model=list[OrderResponse])
async def list_orders(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取当前用户的订单列表（按时间倒序）"""
    orders = db.query(Order).filter(Order.user_id == current_user.id).order_by(Order.created_at.desc()).all()
    result = []
    for od in orders:
        items = [OrderItemResponse(
            goods_id=i.goods_id, name=i.name, price=i.price, qty=i.qty, image_url=i.image_url
        ) for i in od.items]
        result.append(OrderResponse(
            order_no=od.order_no, total_amount=od.total_amount, status=od.status, created_at=od.created_at, items=items
        ))
    return result


@router.delete("/{order_no}")
async def delete_unpaid_order(
    order_no: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    删除未支付订单（前端倒计时归零时触发）
    仅允许删除当前用户、状态为未支付(status=0)的订单
    """
    order = db.query(Order).filter(
        Order.order_no == order_no,
        Order.user_id == current_user.id
    ).first()
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    if order.status != 0:
        raise HTTPException(status_code=400, detail="仅能删除未支付订单")
    try:
        db.delete(order)
        db.commit()
        return {"deleted": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))


